package com.zaimokuza.cn.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zaimokuza.cn.entity.response.ResponseEntity;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * http请求及响应相关工具类
 *
 * @author zaimokuza
 */
public class HttpUtils {

    /**
     * 响应体增加请求成功信息
     *
     * @param response 响应体
     * @throws IOException IOException
     */
    public static void response(HttpServletResponse response, ResponseEntity responseEntity) throws IOException {
        // 设置响应格式
        response.setContentType("application/json;charset=UTF-8");
        // 输出字符流
        PrintWriter printWriter = response.getWriter();
        // 将字符转换成字节数组，指定以UTF-8编码进行转换，使用OutputStream流向客户端输出字节数组
        printWriter.write(new ObjectMapper().writeValueAsString(responseEntity));
        printWriter.flush();
        printWriter.close();
    }

}
